package cn.frank.util;

import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import javax.xml.bind.DatatypeConverter;
import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;

/**
 * @author Frank
 * @date 10-31
 */
public class PostApi {
    //提供君业相关数据
    private final static String CLIENT_ID = "ap-p7nlz98g";
    private final static String CLIENT_SECRET = "dEHltd9AD1FjdsAuXzj8rWMPD46NsydwI1Iag9ta2ws";
    private final static Charset UTF8 = StandardCharsets.UTF_8;
    private final static String api = "/Ds/DescribeRecords";
    private final static String rand = "ipaas_req";
    private final static String filter = "{\"station_code\": \"CB1F1D840DE242B2923435F8EA0B523E\"}";
    private final static String timestamp = String.valueOf(System.currentTimeMillis() / 1000);
    private final static String body = "{\"AssetUUID\": \"671dedf8-8097-46a5-b949-a3727a04b4bd\"," +
            "\"Descending\": true," +
            "\"PageNumber\": 1," +
            "\"PageSize\": 1," +
            "\"filter\":"+filter +
            "}";
    public static String sha256Hex(String s) throws Exception {
        MessageDigest md = MessageDigest.getInstance("SHA-256");
        byte[] d = md.digest(s.getBytes(UTF8));
        return DatatypeConverter.printHexBinary(d).toLowerCase();
    }

    /**
     * sha256_HMAC加密
     * @param message 消息
     * @param secret  秘钥
     * @return 加密后字符串
     */
    public static String hmacSHA256(String secret, String message) throws Exception {
        String hash = "";
        Mac hmacSha256 = Mac.getInstance("HmacSHA256");
        SecretKeySpec secret_key = new SecretKeySpec(secret.getBytes(), "HmacSHA256");
        hmacSha256.init(secret_key);
        byte[] bytes = hmacSha256.doFinal(message.getBytes());
        hash = DatatypeConverter.printHexBinary(bytes).toLowerCase();
        return hash;
    }

    public static String doPost(String url, String body) throws Exception {
        //创建httpclient对象
        CloseableHttpClient httpClient = HttpClients.createDefault();
        CloseableHttpResponse response = null;
        String res = "";
        String shabody = sha256Hex(body);
        String temp = CLIENT_ID + shabody + api + timestamp + rand;
        String sign = hmacSHA256(CLIENT_SECRET,temp);
        String authorization = "ClientId=" + CLIENT_ID + ";" + "Signature=" + sign;
        try {
            // 创建 httppost请求
            HttpPost post = new HttpPost(url);
            //HttpPost post = new HttpPost(url);
            post.addHeader("Content-Type","application/json");
            post.addHeader("X-Project","project-djln6wy4");
            post.addHeader("X-Timestamp",timestamp);
            post.addHeader("X-Rand",rand);
            post.addHeader("Authorization",authorization);

            // 创建请求内容
            StringEntity entity = new StringEntity(body, ContentType.APPLICATION_JSON);
            post.setEntity(entity);
            // 执行http请求
            response = httpClient.execute(post);
            res = EntityUtils.toString(response.getEntity(), "utf-8");
        } catch (IOException e) {
            System.out.println(e.getMessage());
        } finally {
            try {
                if (response != null) {
                    response.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return res;
    }
}
